package org.zxl.iotest.netty.protobuf.client;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.zxl.iotest.netty.protobuf.proto.RegisterEntity;
import org.zxl.iotest.netty.protobuf.proto.StudentEntity;
import org.zxl.iotest.netty.protobuf.util.ClientMessageID;
import org.zxl.iotest.netty.protobuf.util.ZxlMsgSendUtil;

/**
 * @author zhangxiaolong
 * @date 2025-02-16 14:14
 **/
@Slf4j
public class TcpClientService {

    private boolean checkChannel(Channel channel){
        boolean checkResult = channel != null && channel.isActive() && channel.isOpen() && channel.isWritable() && channel.isRegistered();
        System.out.println("checkChannel:" + checkResult);
        return checkResult;
    }

    public void sendHeartbeat(Channel channel){
        if(!checkChannel(channel)){
            return;
        }
        /*Integer msgId = 10000;
        Integer msgLength = 0;
        byte[] msgLengthBytes = ByteUtils.intToBytesBE(msgLength);

        byte[] reqBytes = ByteUtils.concatenateByteArrays(msgId.byteValue(), msgLengthBytes);

        ByteBuf byteBuf = Unpooled.copiedBuffer(reqBytes);*/
        ZxlMsgSendUtil.sendMsg(channel, ClientMessageID.HEARTBEAT, null);
    }

    public void sendRegister(Channel channel){
        if(!checkChannel(channel)){
            return;
        }
//        CommonResult commonResult = CommonResult.newBuilder()
//                .setBSuccess(true)
//                .setIntCodeId(8888)// 使用这个字段作为客户端id；偷懒，没有构造专门用于注册的protobuf类
//                .setStrMsg("success")
//                .build();
//        ZxlMsgSendUtil.sendMsg(channel, ClientMessageID.REGISTER, commonResult);

        RegisterEntity registerEntity = RegisterEntity.newBuilder()
                .setServiceName("Agentless")
                .setServiceUuid(8888L)
                .build();
        ZxlMsgSendUtil.sendMsg(channel, ClientMessageID.REGISTER, registerEntity);


   }

    public void sendCommon(Channel channel){
        if(!checkChannel(channel)){
            return;
        }
//        CommonResult commonResult = CommonResult.newBuilder()
//                .setBSuccess(true)
//                .setIntCodeId(200)
//                .setStrMsg("success")
//                .build();
        StudentEntity studentEntity = StudentEntity.newBuilder()
                .setUuid("123456")
                .setName("zhangsan")
                .build();

        Integer msgId = 12301;
        /*byte[] msgIdBytes = ByteUtils.intToBytesBE(msgId);

        Integer msgLength = commonResult.toByteArray().length;
        byte[] msgLengthBytes = ByteUtils.intToBytesBE(msgLength);

        byte[] reqBytes = ByteUtils.concatenateByteArrays(msgIdBytes, msgLengthBytes, commonResult.toByteArray());

        ByteBuf byteBuf = Unpooled.copiedBuffer(reqBytes);

        channel.writeAndFlush(byteBuf);*/

        ZxlMsgSendUtil.sendMsg(channel, msgId, studentEntity);

        log.info("sendCommon done");
    }
}
